package com.ray.controller;

import com.alibaba.fastjson2.JSON;
import com.ray.pojo.User;
import com.ray.service.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@CrossOrigin
public class JSONController
{
    @Autowired
    private UserServiceImpl userServiceImpl;

    public void setUserServiceImpl(UserServiceImpl userServiceImpl)
    {
        this.userServiceImpl = userServiceImpl;
    }

    @RequestMapping("/json")
    String getJSON(Model model)
    {

        User user = new User();
        user.setName("张三");
        user.setGender(1);
        user.setId(11);

        // 如果出现乱码可以加上以下内容
        // <mvc:annotation-driven>
        //     <mvc:message-converters register-defaults="true">
        //         <!-- 配置Fastjson支持 -->
        //         <bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
        //             <property name="supportedMediaTypes">
        //                 <list>
        //                     <value>text/html;charset=UTF-8</value>
        //                     <value>application/json</value>
        //                 </list>
        //             </property>
        //
        //         </bean>
        //     </mvc:message-converters>
        // </mvc:annotation-driven>

        String s = JSON.toJSONString(user);
        System.out.println(s);
        model.addAttribute("msg", s);
        return "json";
    }

    @RequestMapping("/jsonVUE")
    @ResponseBody
    String getJSONToVue(Model model)
    {

        List<User> allUser = userServiceImpl.getUserList();

        // 如果出现乱码可以加上以下内容
        // <mvc:annotation-driven>
        //     <mvc:message-converters register-defaults="true">
        //         <!-- 配置Fastjson支持 -->
        //         <bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
        //             <property name="supportedMediaTypes">
        //                 <list>
        //                     <value>text/html;charset=UTF-8</value>
        //                     <value>application/json</value>
        //                 </list>
        //             </property>
        //
        //         </bean>
        //     </mvc:message-converters>
        // </mvc:annotation-driven>

        String s = JSON.toJSONString(allUser);
        System.out.println(s);
        model.addAttribute("msg", s);
        return s;
    }
}
